package br.com.financeiro.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

@Component
@SuppressWarnings("unchecked")
public class GenericDao extends HibernateDaoSupport {

	public GenericDao(){};
	
	@Autowired
	public GenericDao(SessionFactory sf) {
		setSessionFactory(sf);
	}
	
	public <T> T buscar(Class <T> classe, int id) {
		return (T) getHibernateTemplate().get(classe, id);
	}
	
	public <T> T buscarUnicoByCamposValores(Class <T> classe, Object[] list) {
		Session session = getSessionFactory().openSession();
		
		Criteria criteria = session.createCriteria(classe);
		for(int i=0; i<list.length; i+=2) {
			criteria.add(Restrictions.eq(String.valueOf(list[i]), list[i+1]));
		}
		
		return (T) criteria.uniqueResult();
	}
	
	public <T> List<T> listar(Class <T> classe, String campo) {
		DetachedCriteria c = DetachedCriteria.forClass(classe);
		if(campo != null)
			c.addOrder(Order.asc(campo));
		return (List<T>) getHibernateTemplate().findByCriteria(c);
	}
	
	public void remover(Object obj) {
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		session.delete(obj);
		session.flush();
	}
	
	public void salvarOuAtualizar(Object obj) {
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		session.saveOrUpdate(obj);
		session.flush();
	}
}
